<template>
  <div class="questions-choice">
    <el-card>
      <!-- 头部文字 + 按钮 -->
      <div class="btn-wrap">
        <span class="text">说明：目前支持学科和关键字条件筛选 </span>
        <el-button
          type="success"
          icon="el-icon-edit"
          size="small"
          @click="$router.push('new')"
          >新增试题</el-button
        >
      </div>
      <!-- from 表单 -->
      <questions-from @search="onSearch"></questions-from>
      <!-- /from 表单 -->
      <!-- tab 切换栏 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick()">
        <el-tab-pane label="全部" name="null"></el-tab-pane>
        <el-tab-pane label="待审核" name="0"></el-tab-pane>
        <el-tab-pane label="已通过" name="1"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
      </el-tabs>

      <el-alert
        class="alert-wrap"
        :title="`数据一共 ${totalCount} 条`"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 表格数据 -->
      <el-table class="my-table" :data="questionsData" style="width: 100%">
        <el-table-column prop="number" label="试题编号" width="120">
        </el-table-column>
        <el-table-column prop="subject" label="学科" width="120">
        </el-table-column>
        <el-table-column prop="catalog" label="目录" width="120">
        </el-table-column>
        <el-table-column prop="questionType" label="题型" width="120">
          <template slot-scope="scope">
            <span>{{ questionType[scope.row.questionType - 1].label }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题干" width="280">
          <template slot-scope="scope">
            <div v-html="scope.row.question"></div>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.addDate | parseTimeByString }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="80">
          <template slot-scope="scope">
            <span>{{ difficulty[scope.row.difficulty - 1].label }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" width="120">
        </el-table-column>
        <el-table-column prop="chkState" label="审核状态" width="120">
          <template slot-scope="scope">
            <span>{{ chkType[scope.row.chkState].label }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="chkRemarks" label="审核意见" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.chkRemarks || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="chkUser" label="审核人" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.chkUser || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.chkState == 1 && scope.row.publishState"
              >已发布</span
            >
            <span v-else-if="scope.row.chkState == 1 && !scope.row.publishState"
              >已下架</span
            >
            <span v-else>待发布</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          fixed="right"
          class="operation-th"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="onQuestionView(scope.row.id)"
              >预览</el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="[1, 2].includes(scope.row.chkState)"
              @click="onCheckShow(scope.row.id)"
              >审核</el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.publishState == 1"
              @click="
                $router.push({ path: 'new', query: { id: scope.row.id } })
              "
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="onPublish(scope.row.id, scope.row.publishState)"
              >{{ scope.row.publishState ? '下架' : '上架' }}</el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.publishState == 1"
              @click="onDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- /试题列表 -->

      <!-- 分页器 -->
      <el-pagination
        class="pagination-right"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageparams.page"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="100"
        layout="prev, pager, next,sizes, jumper"
        :total="totalCount"
      >
      </el-pagination>

      <!-- 试题预览 -->
      <questions-preview
        v-if="isDialogShow"
        v-model="isDialogShow"
        :question-info="questionInfo"
      ></questions-preview>
    </el-card>

    <!-- 试题审核对话框 -->
    <el-dialog
      class="check-dialog"
      title="题目审核"
      :visible.sync="isCheckShow"
      width="400px"
      :before-close="handleClose"
    >
      <questions-check
        v-if="isCheckShow"
        @close="isCheckShow = false"
        @check="onCheck"
      ></questions-check>
    </el-dialog>
  </div>
</template>

<script>
import QuestionsFrom from '../components/questions-from'
import {
  choice,
  detail,
  choiceCheck,
  choicePublish,
  remove
} from '@/api/hmmm/questions'
import {
  difficulty,
  questionType,
  chkType,
  publishType
} from '@/api/hmmm/constants'
import QuestionsPreview from '../components/questions-preview'
import QuestionsCheck from '../components/questions-check'

export default {
  name: 'QuestionsChoice',
  components: {
    QuestionsFrom,
    QuestionsPreview,
    QuestionsCheck
  },
  data() {
    return {
      activeName: 'null',
      totalCount: 0, // 试题总条数
      questionsData: [],
      pageparams: {
        page: 1,
        pagesize: 2
      },
      difficulty: difficulty,
      questionType: questionType,
      chkType: chkType,
      publishType: publishType,
      isDialogShow: false,
      questionInfo: {}, // 试题详情
      isCheckShow: false,
      id: 0,
      from: {} // from表单数据
    }
  },
  created() {
    // 获取精选试题列表
    this.getAllChoice()
  },
  computed: {
    selectTab: function() {
      const obj = { chkState: this.activeName }
      if (this.activeName === 'null') {
        obj.chkState = null
      }
      return obj
    }
  },
  methods: {
    async getAllChoice() {
      const querydata = {
        ...this.from,
        ...this.selectTab,
        ...this.pageparams
      }
      const { data: res } = await choice(querydata)
      console.log(res.items)
      this.totalCount = res.counts
      this.questionsData = res.items
    },
    onSearch(from) {
      console.log(from)
      this.from = from
      this.getAllChoice()
    },
    // 列表切换
    handleClick() {
      this.getAllChoice()
    },
    // pagesize 改变
    handleSizeChange(newPagesize) {
      this.pageparams.pagesize = newPagesize
      this.getAllChoice()
    },
    // page 改变
    handleCurrentChange(newPage) {
      this.pageparams.page = newPage
      this.getAllChoice()
    },
    // 试题预览
    async onQuestionView(id) {
      const { data: res } = await detail({ id })
      this.questionInfo = res
      this.isDialogShow = true
    },
    // 试题审核框弹出
    onCheckShow(id) {
      this.isCheckShow = true
      console.log(id)
      this.id = id
    },
    handleClose() {
      this.isCheckShow = false
    },
    // 试题审核
    async onCheck(from) {
      this.isCheckShow = false
      if (from.chkRemarks.length <= 0) {
        return this.$message.warning('请输入审核意见')
      }
      from.id = this.id
      const { data: res } = await choiceCheck(from)
      if (res.success) {
        this.$message.success('操作成功!')
        return this.getAllChoice()
      }
      this.$message.error('操作成功!')
    },
    // 试题上下架
    onPublish(id, publishState) {
      console.log(publishState)
      const isPublishState = publishState ? 0 : 1
      if (publishState) {
        // 已上架 就下架
        this.$confirm('您确认下架这道题目吗?', '提示', {
          type: 'warning'
        })
          .then(async () => {
            const { data: res } = await choicePublish({
              id,
              publishState: isPublishState
            })
            console.log(res)
            if (res.success) {
              this.getAllChoice()
              return this.$message.success('下架成功!')
            }
            this.$message.error('下架失败')
          })
          .catch(() => {
            this.$message.info('已取消下架')
          })
      } else {
        // 已下架 就上架
        this.$confirm('您确认上架这道题目吗?', '提示', {
          type: 'warning'
        })
          .then(async () => {
            const { data: res } = await choicePublish({
              id,
              publishState: isPublishState
            })
            console.log(res)
            if (res.success) {
              this.getAllChoice()
              return this.$message.success('上架成功!')
            }
            this.$message.error('上架失败')
          })
          .catch(() => {
            this.$message.info('已取消上架')
          })
      }
    },
    // 删除试题
    onDelete(id) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await remove({ id })
          console.log(res)
          console.log(document.querySelectorAll('.my-table tbody tr'))

          if (res.success) {
            //! 修复删除的BUG
            if (document.querySelectorAll('.my-table tbody tr').length / 2 === 1) {
              this.pageparams.page =
                this.pageparams.page > 1 ? this.pageparams.page - 1 : 1
            }
            this.getAllChoice()
            return this.$message.success('删除成功!')
          }
          this.$message.error('删除失败')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  }
}
</script>

<style scoped>
.questions-choice {
  margin: 10px;
}
.btn-wrap {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
span.text {
  font-size: 12px;
  color: pink;
}
.alert-wrap {
  margin-bottom: 15px;
}
.pagination-right {
  text-align: right;
  margin-top: 20px;
}
::v-deep .el-pagination__jump {
  margin-left: 0;
}
::v-deep .el-table_1_column_13 {
  text-align: center;
}
::v-deep .check-dialog .el-dialog__body {
  padding-bottom: 20px;
}
</style>
